/* ansh/builtin.c 
 * 
 * This file is part of ansh. 
 * 
 * ansh is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * ansh is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with ansh. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <sys/wait.h>

#include <ansh/ansh.h>


int do_chdir(int argc, char **argv);
int do_exit(int argc, char **argv);


struct builtin_cmd {
	char 	*cmd;
	int 	len;
	int 	(* do_cmd) (int argc, char **argv);
} builtin[] = {
	{ "cd",  2, do_chdir }, 
	{ "exit", 4, do_exit }, 
	{ NULL, 0, NULL }
};


int do_builtin_cmd(int argc, char **argv) {
	struct builtin_cmd *cmd;

	for (cmd = builtin; cmd->cmd; cmd++) 
		if (!strncmp(argv[0], cmd->cmd, cmd->len)) 
			return cmd->do_cmd(argc, argv);

	return -1;
}

int do_chdir(int argc, char **argv) {
	if (argc == 1) {
		argv[1] = getenv("HOME");

		if (!argv[1]) {
			fprintf(stderr, "cd: $HOME not defined\n");

			return 1;
		}
	}

	if (chdir(argv[1]) < 0) {
		perror(argv[1]);

		return 1;
	}

	getcwd(cwd, PATH_MAX);

	return 0;
}


int do_exit(int argc, char **argv) {
	(void) argc;
	(void) argv;

	exit(EXIT_SUCCESS);

	return 0;
}

